package com.software.levelupandroid.taskIssue.view.activity;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.tabs.TabLayout;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Label;
import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.home.ui.taskByPriority.TaskByPriorityViewModel;
import com.software.levelupandroid.service.NotionService;
import com.software.levelupandroid.taskIssue.presenter.TaskIssuePresenter;
import com.software.levelupandroid.taskIssue.view.IView;
import com.software.levelupandroid.taskIssue.view.adapter.LabelAdapter;
import com.software.levelupandroid.taskIssue.view.fragment.NoticeTaskFragment;
import com.software.levelupandroid.taskIssue.view.fragment.TimingTaskFragment;
import com.software.levelupandroid.taskIssue.view.label.LabelViewModel;
import com.software.levelupandroid.utils.DateUtil;
import com.software.levelupandroid.utils.ExperienceUtil;
import com.software.levelupandroid.utils.ToastUtil;
import com.software.levelupandroid.utils.UserUtil;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class TaskIssueActivity extends AppCompatActivity implements IView {

    private Toolbar toolbarTaskIssue;
    private LabelViewModel labelViewModel;
    private TabLayout tabLayout;
    private ToggleButton tbTaskIOpt;
    List<Label> data;
    private RelativeLayout rlTaskIssuePriority;
    private RelativeLayout rlTaskIssueRepeat;
    private TextView tvTaskIPriority, tvTaskIRepeat,tvTaskITag;
    private EditText edtTaskITitle, edtTaskIContent;
    private Button btnTaskISave;
    private TaskIssuePresenter taskIssuePresenter;
    private ImageView tvTaskIImg;
    private Task task = new Task();
    private int flag;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_issue);

        Intent intent = getIntent();
        Task intentTask = (Task) intent.getSerializableExtra("task");
        flag = intent.getIntExtra("flag", 0);
        System.out.println(flag);
        if (intentTask != null){
            task = intentTask;
        }

        taskIssuePresenter = new TaskIssuePresenter(this);

        rlTaskIssuePriority = findViewById(R.id.rl_taskI_priority);
        rlTaskIssueRepeat = findViewById(R.id.rl_taskI_repeat);
        tvTaskIPriority = findViewById(R.id.tv_taskI_priority);
        tvTaskIRepeat = findViewById(R.id.tv_taskI_repeat);
        tvTaskITag = findViewById(R.id.tv_taskI_tag);
        tvTaskIImg = findViewById(R.id.iv_taskI_img);

        tbTaskIOpt = findViewById(R.id.tb_taskI_opt);
        edtTaskITitle = findViewById(R.id.edt_taskI_title);
        edtTaskIContent = findViewById(R.id.edt_taskI_content);
        btnTaskISave = findViewById(R.id.btn_taskI_save);

        //初始化工具栏
        initToolbar();

        initViewModel();
        observeLiveData();
        labelViewModel.getLabel(TaskIssueActivity.this);

        //设置标签选择时的监听器
        setTabSelectedListener();

        //初始化任务编辑界面时，默认显示通知型任务布局
        showNotificationLayout();

        if (task != null && flag == 1){
            tbTaskIOpt.setChecked(task.getStatus() == 1);
            edtTaskITitle.setText(task.getTaskTitle());
            edtTaskIContent.setText(task.getContent());
            if (task.getTaskType() == 2){
                tabLayout.selectTab(tabLayout.getTabAt(1));
                showTimerLayout();
            }else {
                tabLayout.selectTab(tabLayout.getTabAt(0));
                showNotificationLayout();
            }
            switch (task.getPriority()){
                case 0: //不重要不紧急
                    tvTaskIPriority.setText("不重要不紧急");
                    task.setPriority(0);
                    break;
                case 1: //重要不紧急
                    tvTaskIPriority.setText("重要不紧急");
                    task.setPriority(1);
                    break;
                case 2: //不重要紧急
                    tvTaskIPriority.setText("不重要紧急");
                    task.setPriority(2);
                    break;
                case 3: //重要且紧急
                    tvTaskIPriority.setText("重要且紧急");
                    break;
                default:
                    break;
            }
            String[] items = {"不重复", "每日重复一次", "每周重复一次", "每月重复一次", "每年重复一次", "每个工作日重复"};
            switch (task.getIsRecurring()) {
                case 0:
                    tvTaskIRepeat.setText(items[0]);
                    break;
                case 1:
                    tvTaskIRepeat.setText(items[1]);
                    break;
                case 2:
                    tvTaskIRepeat.setText(items[2]);
                    break;
                case 3:
                    tvTaskIRepeat.setText(items[3]);
                    break;
                case 4:
                    tvTaskIRepeat.setText(items[4]);
                    break;
                case 5:
                    tvTaskIRepeat.setText(items[5]);
                    break;
            }

        }else {
            task.setTaskType(1);
        }

        //对其他控件设置监听器
        setListener();
    }

    public Task getTask(){
        return task;
    }

    //对其他控件设置监听器
    private void setListener() {
        //label的选择
        tvTaskITag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 参数2：设置BottomSheetDialog的主题样式；将背景设置为transparent，这样我们写的shape_bottom_sheet_dialog.xml才会起作用
                BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(TaskIssueActivity.this, R.style.BottomSheetDialog);

                View bottomView = LayoutInflater.from(getBaseContext()).inflate(R.layout.bottom_sheet_layout, null);

                bottomSheetDialog.setContentView(bottomView);

                ListView listView = (ListView) bottomView.findViewById(R.id.lv);
                //实例化适配器

                LabelAdapter adapter = new LabelAdapter(data, getBaseContext(), R.layout.label_item,tvTaskITag,tvTaskIImg);

                listView.setAdapter(adapter);

                bottomSheetDialog.show();
            }
        });
        //设置rlTaskIssuePriority（选择任务的优先级的布局）点击事件监听器
        rlTaskIssuePriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriorityBottomSheetDialog();
            }
        });

        //设置rlTaskIssueRepeat（选择是否重复的布局）点击事件监听器
        rlTaskIssueRepeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRepeatAlertDialog();
            }
        });

        //保存按钮的监听器
        btnTaskISave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                task.setTaskTitle(String.valueOf(edtTaskITitle.getText()));
                task.setContent(String.valueOf(edtTaskIContent.getText()));
                task.setStatus(0);
                //TODO 设置任务发布者的id(后端会通过token获取用户的信息)
//                task.setUserId(1);
                if (task.getCreatedAt() == null){
                    task.setCreatedAt(DateUtil.getNowTime());
                }


                if (task.getTaskType() == 1){
                    task.setEndTime(null);
                    task.setRemind1(null);
                    task.setRemind2(null);
                    task.setRemind3(null);
                    if (task.getStartTime() == null){
                        task.setTaskType(0);
                    }
                }
                if (task.getPriority() == null){
                    task.setPriority(0);
                }
                if (task.getIsRecurring() == null){
                    task.setIsRecurring(0);
                }

                //调用Presenter的接口实现任务的新增
                if (flag == 0){
                    taskIssuePresenter.issueTask(task, TaskIssueActivity.this);
                }else {
                    String updateTime = DateUtil.getNowTime();
                    task.setUpdatedAt(updateTime);
                    taskIssuePresenter.updateTask(task, TaskIssueActivity.this);
                }

                System.out.println(task);
            }
        });

        tbTaskIOpt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                double experience = ExperienceUtil.getExperience(task);
                User user = UserUtil.getUser(TaskIssueActivity.this);

                if (b){
                    task.setStatus(1);
                    //更新用户经验值
                    user.setExperience(user.getExperience() + experience);
                    taskIssuePresenter.updateExperience(user.getExperience(), TaskIssueActivity.this);
                    UserUtil.saveUser(user, TaskIssueActivity.this);
                }else {
                    if (task.getStartTime() != null){
                        String start = task.getStartTime();
                        Long startLong = DateUtil.convertStringToLong(start, "yyyy年MM月dd日 HH:mm");
                        Long nowLong = DateUtil.getNowTimeLong();
                        if (startLong < nowLong){
                            task.setStatus(-1);
                        }else {
                            task.setStatus(0);
                        }
                    }
                    //更新用户经验值
                    user.setExperience(user.getExperience() - experience);
                    taskIssuePresenter.updateExperience(user.getExperience(), TaskIssueActivity.this);
                    UserUtil.saveUser(user, TaskIssueActivity.this);
                }
                //更新任务状态
                taskIssuePresenter.isFinishTask(task, TaskIssueActivity.this);
            }
        });
    }

    //展开关于重复选项的弹窗
    private void showRepeatAlertDialog() {
        String[] items = {"不重复", "每日重复一次", "每周重复一次", "每月重复一次", "每年重复一次", "每个工作日重复"};
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        //设置弹窗的每个item的点击事件
        dialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                tvTaskIRepeat.setText(items[i]);
                task.setIsRecurring(i);
                switch (i){
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                }
            }
        });
        dialog.show();
    }

    //展开关于优先级选项的底部弹窗
    @SuppressLint("MissingInflatedId")
    private void showPriorityBottomSheetDialog() {
        //定义底部弹窗，并展示
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this, R.style.BottomSheetDialog);
        View bottomView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog_task_issue, null);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.show();

        //控件绑定
        TextView tvTaskIPriority0 = bottomView.findViewById(R.id.tv_bsd_taskI_priority0);
        TextView tvTaskIPriority1 = bottomView.findViewById(R.id.tv_bsd_taskI_priority1);
        TextView tvTaskIPriority2 = bottomView.findViewById(R.id.tv_bsd_taskI_priority2);
        TextView tvTaskIPriority3 = bottomView.findViewById(R.id.tv_bsd_taskI_priority3);
        TextView tvTaskICancel = bottomView.findViewById(R.id.tv_bsd_taskI_cancel);

        //设置底部弹窗的各个按钮的点击事件
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.tv_bsd_taskI_priority0: //不重要不紧急
                        tvTaskIPriority.setText(tvTaskIPriority0.getText());
                        task.setPriority(0);
                        break;
                    case R.id.tv_bsd_taskI_priority1: //重要不紧急
                        tvTaskIPriority.setText(tvTaskIPriority1.getText());
                        task.setPriority(1);
                        break;
                    case R.id.tv_bsd_taskI_priority2: //不重要紧急
                        tvTaskIPriority.setText(tvTaskIPriority2.getText());
                        task.setPriority(2);
                        break;
                    case R.id.tv_bsd_taskI_priority3: //重要且紧急
                        tvTaskIPriority.setText(tvTaskIPriority3.getText());
                        task.setPriority(3);
                        break;
                    case R.id.tv_bsd_taskI_cancel: //取消按钮
                        break;
                }
                bottomSheetDialog.dismiss();
            }
        };
        tvTaskIPriority0.setOnClickListener(clickListener);
        tvTaskIPriority1.setOnClickListener(clickListener);
        tvTaskIPriority2.setOnClickListener(clickListener);
        tvTaskIPriority3.setOnClickListener(clickListener);
        tvTaskICancel.setOnClickListener(clickListener);
    }

    //设置标签选择时的监听器
    private void setTabSelectedListener() {
        tabLayout = findViewById(R.id.tl_taskI_tabLayout);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            // 根据选择的 tab 来切换布局
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0: //通知型任务
                        tab.setIcon(R.drawable.baseline_notifications_blue_24);
                        task.setTaskType(1);
                        showNotificationLayout();
                        break;
                    case 1: //计时型任务
                        tab.setIcon(R.drawable.baseline_timer_blue_24);
                        task.setTaskType(2);
                        showTimerLayout();
                        break;
                    default:
                        break;
                }
            }

            @Override
            // 当 tab 被取消选择时
            public void onTabUnselected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0:
                        tab.setIcon(R.drawable.baseline_notifications_black_24);
                        break;
                    case 1:
                        tab.setIcon(R.drawable.baseline_timer_black_24);
                        break;
                    default:
                        break;
                }
            }

            @Override
            // 当 tab 被重新选择时
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    //显示计时型任务布局
    private void showTimerLayout() {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_taskI_container, new TimingTaskFragment())
                .commit();
    }

    //显示通知型任务布局
    private void showNotificationLayout() {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_taskI_container, new NoticeTaskFragment())
                .commit();
    }

    //初始化工具栏
    private void initToolbar() {
        toolbarTaskIssue = findViewById(R.id.toolbar_taskIssue);
        setSupportActionBar(toolbarTaskIssue);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
            actionBar.setDisplayShowTitleEnabled(false);
    }

    /**
     * 加载toolbar上的菜单资源
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_task_issue_menu,menu);
        return true;
    }

    /**
     * 设置菜单项中的点击事件（删除按钮的点击事件）
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
//            case R.id.menu_taskDelete:
//                Toast.makeText(this, "delete task", Toast.LENGTH_SHORT).show();
//                return true;
            case R.id.menu_taskDelete0:
                taskIssuePresenter.deleteTask(task, TaskIssueActivity.this);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 向上导航，即返回上一级的Activity
     * @return
     */
    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    /**
     * IView接口中新增任务成功的方法
     * @param task
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void issueTaskSuccess(Task task) {
        if (task.getTaskType() == 1 && task.getStartTime() != null){
            Long aLong = DateUtil.convertStringToLong(task.getStartTime(), "yyyy年MM月dd日 HH:mm");
            //设置提醒
            Intent intent = new Intent(this, NotionService.class);
            intent.putExtra("title", task.getTaskTitle());
            intent.putExtra("content", task.getContent());
            intent.putExtra("task_type", task.getTaskType());
            PendingIntent service = PendingIntent.getService(this, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, aLong, service);
        }

        if (flag == 0){
            ToastUtil.showToastOnUI(TaskIssueActivity.this, "新增任务成功");
        }else {
            ToastUtil.showToastOnUI(TaskIssueActivity.this, "更新任务成功");
        }

        finish();
    }

    /**
     * IView接口中新增任务失败的方法
     * @param msg
     */
    @Override
    public void issueTaskFailure(String msg) {
        if (flag == 0){
            ToastUtil.showToastOnUI(TaskIssueActivity.this, "新增任务失败");
        }else {
            ToastUtil.showToastOnUI(TaskIssueActivity.this, "更新任务失败");
        }

        Log.e("error", msg);
    }

    /**
     * IView接口中删除任务成功
     * @param task
     */
    @Override
    public void deleteTaskSuccess(Task task) {
        finish();
        ToastUtil.showToastOnUI(TaskIssueActivity.this, "删除任务成功");
    }

    /**
     * IView接口中删除任务失败
     * @param msg
     */
    @Override
    public void deleteTaskFailure(String msg) {
        ToastUtil.showToastOnUI(TaskIssueActivity.this, msg);
    }

    /**
     * IView接口中任务状态更新成功
     * @param task
     */
    @Override
    public void isFinishSuccess(Task task) {
        ToastUtil.showToastOnUI(TaskIssueActivity.this, "任务状态更新成功");
    }

    /**
     * IView接口中任务状态更新失败
     * @param msg
     */
    @Override
    public void isFinishFailure(String msg) {
        ToastUtil.showToastOnUI(TaskIssueActivity.this, msg);
    }

    /**
     * IView接口中用户经验值更新成功
     * @param data
     */
    @Override
    public void updateExperienceSuccess(String data) {

    }

    /**
     * IView接口中用户经验值更新失败
     * @param msg
     */
    @Override
    public void updateExperienceFailure(String msg) {

    }


    private void initViewModel() {
        ViewModelProvider viewModelProvider = new ViewModelProvider(this);
        labelViewModel = viewModelProvider.get(LabelViewModel.class);

    }
    private void observeLiveData() {
        labelViewModel.getLabelLiveData().observe(this, new Observer<Resource<List<Label>>>() {
            @Override
            public void onChanged(Resource<List<Label>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        //TODO 已经获得tasks，待通过Adapter加载
                        data = listResource.getData();
                        for(int i = 0; i < data.size(); i++){
                            System.out.println(R.drawable.text);
                            System.out.println("labelViewModel.getLabelLiveData().observe()"+listResource.getData().get(i).toString());
                        }

                    }else if (listResource.isFailure()){
                        ToastUtil.showToastOnUI(TaskIssueActivity.this, listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });
    }

}